# -*- coding: utf-8 -*-
import logging
from google.appengine.ext import webapp

from dbmodel import User

class Handler(webapp.RequestHandler):
	""" Parent class for all of our handlers.
		Takes care of turning the query string into a dict
		Here would also be a good place to do session stuff
		NOTE: When you extend this class it is required that you
		call requiredParams() even if it is empty when you satrt
		get or post.
	"""
	def initialize(self, request, response):
		webapp.RequestHandler.initialize(self, request, response)

		# Take the query string in this format: ?key=value&key=value
		# and generate a dictionary
		self.params = dict([i.split('=') for i in self.request.query_string.split('&') if len(i) > 0])

		self.sID = ''
		self.user = None


	def requiredParams(self, *keys):
		pkeys = self.params.keys()
		for key in list(keys):
			if key not in pkeys:
				self.response.set_status(400, "No %s in request" % (key))
				return False

		if 'sID' in keys:
			self.sID = self.params['sID']

			query = User.gql("WHERE currentSID = :1", self.sID)
			logging.info(query.count())
			self.user = query.get()
			logging.info(str(self.user))

			if not self.user:
				self.response.set_status(400, "Bad Session ID")
				return False
		else:
			self.user = None

		return True
